import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {
  NzMessageService,
  UploadFile,
  UploadXHRArgs,
  fadeMotion,
  UploadFilter,
  UploadChangeParam,
  NzUploadComponent,
} from 'ng-zorro-antd';
import { debug } from 'util';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType, HttpResponse } from '@angular/common/http';
import { _HttpClient } from '@delon/theme';
import { ServerResult } from '../../../infrastructure/server.result';
import { plainToClass } from 'class-transformer';
import { Observable, Observer } from 'rxjs';
import { UploadedResultModel } from '../../../modes/uploaded.result.model';
import { Router } from '@angular/router';
import { APPHOST } from '../../../shared/index';

@Component({
  selector: 'video-form',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class VideoFormComponent implements OnInit {

  @ViewChild('nzUploader', { read: NzUploadComponent, static: true }) nzUploader: NzUploadComponent;
  title: string = '';

  fileType: string = 'video/x-flv,video/avi,video/mp4';
  filters: UploadFilter[] = [
    {
      name: 'type',
      fn: (fileList: UploadFile[]) => {
        var types = this.fileType.split(',');
        //console.log(`type`);
        //console.log(types);
        //console.log(fileList);
        const filterFiles = fileList.filter(w => ~types.indexOf(w.type));
        if (filterFiles.length !== fileList.length) {
          this.msg.error(`包含文件格式不正确，支持mp4,flv,avi格式`);
          return filterFiles;
        }
        return fileList;
      },
    },
    {
      name: 'async',
      fn: (fileList: UploadFile[]) => {
        console.log(`async`);
        console.log(fileList);
        return new Observable((observer: Observer<UploadFile[]>) => {
          console.log(`observer`);
          console.log(fileList);
          observer.next(fileList);
          observer.complete();
        });
      },
    },
  ];
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true,
  };
  fileList = [];
  previewUrl: string | undefined = '';
  previewVisible = false;
  action = `${APPHOST}/api/video/upload/`;

  handlePreview = (file: UploadFile) => {
    this.previewUrl = file.data.videoUrl;
    //this.previewVisible = true;
    //https://github.com/giuseppe-dandrea/Stream-to-VLC
    window.location.href = 'vlcs:' + this.previewUrl;
  };
  ringWasPlaced = (event) => {
    console.log(event);
  };


  customRequest = (args: UploadXHRArgs) => {


    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', args.file as any);
    const req = new HttpRequest('POST', args.action!, formData, {
      reportProgress: true,
      withCredentials: false,
    });
    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total! > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          // 处理上传进度条，必须指定 `percent` 属性来表示进度
          args.onProgress!(event, args.file!);
        } else if (event instanceof HttpResponse) {
          // 处理成功

          const responseData = event.body;
          const result = plainToClass(ServerResult, responseData) as ServerResult<UploadedResultModel>;

          if (!result.isOK()) {
            this.msg.create('error', result.errorMsg);
            args.onError!(Error(result.errorMsg), args.file!);
            this.fileList.pop();
          } else {


            const item = this.fileList.pop();
            item.thumbUrl = `${result.data.coverUrl}?width=300`;
            item.data = result.data;
            this.fileList.push(item);
            args.onSuccess!(event.body, args.file!, event);


          }
        }
      },
      err => {
        this.fileList.pop();
        args.onError!(err, args.file!);
      },
    );
  };
  handleChange = (param: UploadChangeParam) => {
    console.log(param);
  };

  constructor(private fb: FormBuilder, private msg: NzMessageService, private cdr: ChangeDetectorRef, private http: HttpClient, public _http: _HttpClient, private router: Router) {
  }

  ngOnInit(): void {

  }


  ngAfterViewInit(): void {

  }

  submit(event) {
    console.log(event);
    if (!this.title || this.title == '') {
      this.msg.create('error', '请输入标题');
    } else if (this.fileList.length < 1 || !this.fileList[0].data) {
      this.msg.create('error', '请上传视频文件');
    } else {
      const transformRequest = (obj) => {
        const str = [];
        for (const p in obj)
          str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        return str.join('&');
      };

      this.http.post(`${APPHOST}/api/video/add`, transformRequest({
        title: this.title,
        ...this.fileList[0].data,
      }), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }).subscribe(
        (responseData: any) => {
          const result = plainToClass(ServerResult, responseData) as ServerResult<any>;
          if (!result.isOK()) {
            this.msg.create('error', result.errorMsg);
          } else {
            this.router.navigate(['cms/video']);
          }
        },
        err => {
          this.msg.create('error', '网络请求错误');
        },
      );

    }
  }
}
